//
//  detailClientViewController.m
//  LazyCat
//
//  Created by rocky on 16/1/4.
//  Copyright (c) 2016年 zhanshu. All rights reserved.
//

#import "detailClientViewController.h"
#import "NJKWebViewProgress.h"
#import "NJKWebViewProgressView.h"
#import "JsWebviewNativeManager.h"
#import "AFNetworkHandler.h"
#import "MSBluetoothManager.h"

@interface detailClientViewController ()<UIWebViewDelegate,NJKWebViewProgressDelegate>

{
    NJKWebViewProgressView *_webViewProgressView;
    NJKWebViewProgress *_webViewProgress;
}
@property (nonatomic,strong) UIWebView *webV;
@property (nonatomic,strong) NSString *orderNum;
@property (nonatomic,strong) NSDictionary *dataDic;
@property (nonatomic,strong) UIView *noNetView;//无网络视图
@property (nonatomic,strong) NSString *url;

@end

@implementation detailClientViewController
- (void)backAction:(UIButton *)btn{
    if (![self.webV canGoBack]) {//判断是否可以HTML返回
        if (!self.navigationController.viewControllers) {
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }else {
            NSArray *arr = self.navigationController.viewControllers;
            [self.navigationController popToViewController:arr[2] animated:YES];
        }
    }else {
        [self.webV goBack];
    }
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (kNetworkNotReachability) {
        [[MessShowView share] showWithMess:@"当前网络不给力"];
        self.webV.hidden = YES;
        self.noNetView.hidden = NO;
    }else {
        self.noNetView.hidden = YES;
        self.webV.hidden = NO;
        [self.webV loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNav:@"搜索详情" doBack:YES];
    self.view.backgroundColor = BackColor;
    UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(0, 63, ScreenWidth, 1)];
    lineV.alpha = 0.2;
    lineV.backgroundColor = [UIColor lightGrayColor];
    [self.navBar addSubview:lineV];
    self.webV = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64)];
    self.webV.delegate = self;
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    NSString *iptype = [userDefaul objectForKey:@"iptype"];
    NSString *banben = [userDefaul objectForKey:@"banben"];
    if ([self.isFrom isEqualToString:@"0"]) {
        self.url = [NSString stringWithFormat:serverSearchUrl,[AppData share].username,[Utils md5SignStr],iptype,banben,self.key];
        self.url = [self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [self.webV loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    }else if ([self.isFrom isEqualToString:@"1"]) {
        self.url = [NSString stringWithFormat:expressSearchUrl,[AppData share].username,[Utils md5SignStr],iptype,banben,self.key];
        self.url = [self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [self.webV loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    }
    [self.webV.scrollView setScrollEnabled:YES];
    self.webV.backgroundColor = BackColor;
    [self.view addSubview:self.webV];
    self.webV.scrollView.showsVerticalScrollIndicator = NO;
    _webViewProgress = [[NJKWebViewProgress alloc]init];
    self.webV.delegate = _webViewProgress;
    _webViewProgress.webViewProxyDelegate = self;
    _webViewProgress.progressDelegate = self;
    CGRect navBounds = self.navBar.bounds;
    CGRect barFrame = CGRectMake(0, navBounds.size.height - 2, navBounds.size.width, 2);
    _webViewProgressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _webViewProgressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [_webViewProgressView setProgress:0 animated:YES];
    [self.navBar addSubview:_webViewProgressView];
    
    self.noNetView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 104)];
    self.noNetView.hidden = YES;
    self.noNetView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.noNetView];
    UIImageView *netImg = [[UIImageView alloc] initWithFrame:CGRectMake((ScreenWidth-100)/2, 70, 100, 90)];
    netImg.image = [UIImage imageNamed:@"无网络_r1_c1"];
    [self.noNetView addSubview:netImg];
    UILabel *netFail = [[UILabel alloc] initWithFrame:CGRectMake(0, 180, ScreenWidth, 20)];
    netFail.text = @"网络请求失败";
    netFail.textAlignment = NSTextAlignmentCenter;
    netFail.font = [UIFont systemFontOfSize:16];
    [self.noNetView addSubview:netFail];
    UIButton *refresh = [[UIButton alloc] initWithFrame:CGRectMake((ScreenWidth-120)/2, 210, 120, 40)];
    [refresh setImage:[UIImage imageNamed:@"无网络_r3_c2 下午4.23.04"] forState:UIControlStateNormal];
    refresh.adjustsImageWhenHighlighted = NO;
    [self.noNetView addSubview:refresh];
    [refresh addTarget:self action:@selector(refreshV) forControlEvents:UIControlEventTouchUpInside];//刷新
}
-(void)refreshV {//刷新按钮
    if (kNetworkNotReachability) {
        [[MessShowView share] showWithMess:@"当前网络不给力"];
        self.webV.hidden = YES;
        self.noNetView.hidden = NO;
    }else {
        self.noNetView.hidden = YES;
        self.webV.hidden = NO;
        [self.webV loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    }
}
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress {
    [_webViewProgressView setProgress:progress animated:YES];
}
-(void)webViewDidStartLoad:(UIWebView *)webView {
    [_webViewProgressView setProgress:0 animated:YES];
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
    [_webViewProgressView setProgress:1 animated:YES];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *requestString = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSLog(@"%@",requestString);
    NSArray *components = [requestString componentsSeparatedByString:@"@"];//提交请求时候分割参数的分隔符
    if (components.count == 2) {
        NSArray *resultArr = [components[1] componentsSeparatedByString:@":"];
        NSLog(@"=====================%ld",(unsigned long)resultArr.count);
        NSLog(@"%@ ==== %@ === %@",resultArr[0],resultArr[1],resultArr[2]);
        if ([resultArr count] > 1 && [(NSString *)[resultArr objectAtIndex:0] isEqualToString:@"lanmao_ios"]) {
            //过滤请求是否是我们需要的.不需要的请求不进入条件
            NSString *actionStr = [resultArr objectAtIndex:1];
            NSLog(@"%@",actionStr);
            if ([actionStr isEqualToString:@"printReceipt"]) {
                NSLog(@"+++++++++++++++");
                self.orderNum = [resultArr objectAtIndex:2];
                NSLog(@"%@=============%@",self.orderNum,resultArr[2]);
                [self printXP];
                return NO;
            }else {
                NSLog(@"----------------");
            }
        }
    }
    return YES;
}
-(void)printXP {//打印小票
    NSString *url = [NSString stringWithFormat:orderDetailUrl,self.orderNum];
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        NSDictionary *dic = result;
        NSString *r = dic[@"r"];
        if ([r isEqualToString:@"T"]) {
            self.dataDic = [dic[@"orders"] objectAtIndex:0];
            [self touchesBegan];
        }else {
            [[MessShowView share] showWithMess:@"打印失败" login:NO];
        }
    }];
}
- (void)touchesBegan {
    NSString *RStr = @"2764";
    NSMutableString *str = [NSMutableString new];
    [str appendFormat:@"%c", 28];
    [str appendFormat:@"%c", 33];
    [str appendFormat:@"%c", 8];
    [[MSBluetoothManager shareInstance].cbPeripheral writeValue:[str dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)] forCharacteristic:[MSBluetoothManager shareInstance].cbCharacteristcs type:CBCharacteristicWriteWithResponse];
    NSString *shopName = [ShopCommonModel share].shopname; // 商家名称
    NSString *orderno = [self.dataDic objectForKey:@"orderno"]; // 订单号
    NSString *createtime = [self.dataDic objectForKey:@"createtime"]; // 下单时间
    NSString *sendDay = [self.dataDic objectForKey:@"sendtime"]; // 配送日期
    NSString *sendtime = [self.dataDic objectForKey:@"sendtimerang"]; // 配送时间
    NSString *mobile = [self.dataDic objectForKey:@"mobile"]; // 联系电话
    NSString *address = [self.dataDic objectForKey:@"address"]; // 联系地址
    NSArray *temArr = [self.dataDic objectForKey:@"products"]; // 商品数组
    NSString *totalmoney = [self.dataDic objectForKey:@"totalmoney"]; // 总金额
    NSString *productsnum = [self.dataDic objectForKey:@"productsnum"]; // 商品数量
    NSString *paytypestr = [self.dataDic objectForKey:@"paytypestr"]; // 支付方式
    
    NSString *onlinePay = [self.dataDic objectForKey:@"realpayamount"];
    NSString *yuePay = [self.dataDic objectForKey:@"yue"];
    NSString *jifenPay = [self.dataDic objectForKey:@"fenxiangjf"];
    NSString *yhqPay = [self.dataDic objectForKey:@"couponpay"];
    
    NSString *lcatcoupanpaytl = [self.dataDic objectForKey:@"lcatcoupanpaytl"];//懒猫券抵扣总金额
    NSString *product = @"";
    for (int i = 0; i < temArr.count; i++) {
        NSString *pName = [temArr[i] objectForKey:@"productname"]; // 商品名字
        NSString *price = [temArr[i] objectForKey:@"price"]; // 商品价格
        NSString *numbuy = [temArr[i] objectForKey:@"numbuy"]; // 商品数量
        NSString *lcatcouponpay = [temArr[i] objectForKey:@"lcatcouponpay"]; //懒猫券抵扣（单个商品）金额
        if (lcatcouponpay.length == 0 || [lcatcouponpay floatValue] <= 0) {
            lcatcouponpay = @"";
            product = [NSString stringWithFormat:@"%@\n%@\n                x%@       %@\n",product,pName,numbuy,price];
            
        }else{
            product = [NSString stringWithFormat:@"%@\n%@\n                x%@       %@\n             懒猫券抵扣 ：%@\n",product,pName,numbuy,price,lcatcouponpay];
            
        }
        
    }
    //    RStr = @"杜博 你好呀!!!\n我很好\n啦啦啦\n啦啦啦\n啦啦\n啦啦啦\n啦啦啦\n啦啦\n";
    if (lcatcoupanpaytl.length == 0 || [lcatcoupanpaytl floatValue] <= 0) {
        RStr = [NSString stringWithFormat:@"\n商家名称:%@\n订单号:%@\n下单时间:%@\n配送日期:%@\n配送时间:%@\n联系电话:%@\n联系地址:%@\n------------------------------\n商品名称       数量      金额\n------------------------------\n%@\n------------------------------\n商品总数量:%@\n支付方式:%@\n在线支付:%@\n余额支付:%@\n积分抵扣:%@\n优惠券抵扣:%@\n消费总金额:%@\n------------------------------\n 懒猫社长\n\n\n",shopName,orderno,createtime,sendDay,sendtime,mobile,address,product,productsnum,paytypestr,onlinePay,yuePay,jifenPay,yhqPay,totalmoney];
    }else{
        RStr = [NSString stringWithFormat:@"\n商家名称:%@\n订单号:%@\n下单时间:%@\n配送日期:%@\n配送时间:%@\n联系电话:%@\n联系地址:%@\n------------------------------\n商品名称       数量      金额\n------------------------------\n%@\n------------------------------\n商品总数量:%@\n支付方式:%@\n在线支付:%@\n余额支付:%@\n积分抵扣:%@\n懒猫券抵扣:%@\n优惠券抵扣:%@\n消费总金额:%@\n------------------------------\n 懒猫社长\n\n\n",shopName,orderno,createtime,sendDay,sendtime,mobile,address,product,productsnum,paytypestr,onlinePay,yuePay,jifenPay,lcatcoupanpaytl,yhqPay,totalmoney];
    }
    
    NSData *nsdata =  [RStr dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
    [[MSBluetoothManager shareInstance] writeData:nsdata];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
